<template>

    <div class="app-container" v-if="canList">
        <div class="filter-container">
            <el-input @keyup.enter.native="handleFilter" class="filter-item input" placeholder="产品名"
                      style="width: 200px;"
                      v-model="listQuery.name">
            </el-input>


            <el-select @change='handleFilter' class="filter-item input" clearable placeholder="是否推荐"
                       style="width: 130px"
                       v-model="listQuery.top">
                <el-option :key="item" :label="item" :value="index" v-for="(item,index) in  topOptions">
                </el-option>
            </el-select>

            <el-select @change='handleFilter' class="filter-item input" clearable placeholder="是否上架"
                       style="width: 130px"
                       v-model="listQuery.shelf">
                <el-option :key="item" :label="item" :value="index" v-for="(item,index) in  shelfOptions">
                </el-option>
            </el-select>

            <div style="display: inline-block">

                <el-button @click="handleFilter" class="filter-item" icon="el-icon-search" style="margin-left: 10px;"
                           type="primary"
                           v-waves>查找
                </el-button>
                <el-button @click="handleCreate" class="filter-item" icon="el-icon-edit" style="margin-left: 10px;"
                           type="primary" v-if="canSave">添加
                </el-button>
                <!--                <el-button :loading="downloadLoading" @click="handleDownload" class="filter-item" icon="el-icon-download" type="primary"-->
                <!--                           v-waves>导出-->
                <!--                </el-button>-->
            </div>
        </div>


        <el-table :data="list" :key='tableKey' border fit highlight-current-row style="width: 100%;"
                  v-loading="listLoading">
            <el-table-column align="center" label="序号">
                <template slot-scope="scope">
                    <span>{{scope.$index+1}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="产品名">
                <template slot-scope="scope">
                    <span>{{scope.row.name}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="库存">
                <template slot-scope="scope">
                    <span>{{scope.row.stock}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="单位">
                <template slot-scope="scope">
                    <span>{{scope.row.unit}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="原价">
                <template slot-scope="scope">
                    <span>{{scope.row.oldPrice}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="现价">
                <template slot-scope="scope">
                    <span>{{scope.row.nowPrice}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="必须积分">
                <template slot-scope="scope">
                    <span>{{scope.row.point}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="满免数量">
                <template slot-scope="scope">
                    <span>{{scope.row.logFreeNum}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="未满邮费">
                <template slot-scope="scope">
                    <span>{{scope.row.logFee}}</span>
                </template>
            </el-table-column>
<!--            <el-table-column align="center" label="单位"  >-->
<!--                <template slot-scope="scope">-->
<!--                    <span>{{scope.row.unit}}</span>-->
<!--                </template>-->
<!--            </el-table-column>-->
            <el-table-column align="center" label="排序,越大越靠前">
                <template slot-scope="scope">
                    <span>{{scope.row.idx}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="描述">
                <template slot-scope="scope">
                    <span>{{scope.row.info}}</span>
                </template>
            </el-table-column>
<!--            <el-table-column align="center" label="重量">-->
<!--                <template slot-scope="scope">-->
<!--                    <span>{{scope.row.weight}}</span>-->
<!--                </template>-->
<!--            </el-table-column>-->
            <el-table-column align="center" label="是否推荐">
                <template slot-scope="scope">
                                                <span>

                         <el-tag :type="tagTypes[scope.row.top]">     {{topOptions[scope.row.top]}}</el-tag>

                        </span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="是否上架">
                <template slot-scope="scope">
                                                <span>

                         <el-tag :type="tagTypes[scope.row.shelf]">     {{shelfOptions[scope.row.shelf]}}</el-tag>

                        </span>
                </template>
            </el-table-column>

            <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="230">
                <template slot-scope="scope">
                    <el-button @click="handleUpdate(scope)" size="mini" type="primary" v-if="canUpdate">编辑</el-button>
                    <el-button @click="handleDelete(scope)" size="mini" type="danger"
                               v-if="canSave">删除
                    </el-button>
                </template>
            </el-table-column>

        </el-table>

        <div class="pagination-container" style="margin-top: 20px">
            <el-pagination :current-page="listQuery.page" :page-size="listQuery.limit" :page-sizes="[10,20,30, 50]"
                           :total="total" @current-change="handleCurrentChange" @size-change="handleSizeChange"
                           background layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
        </div>

        <el-dialog width="65%" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form :model="temp" :rules="rules" label-position="left" label-width="120px" ref="dataForm"
                     style='width: 70%; margin-left:50px;'>
                <el-form-item label="产品名" prop="name">
                    <el-input v-model="temp.name"></el-input>
                </el-form-item>
                <el-form-item label="选择分类" prop="type" v-if="types">
                    <el-select multiple placeholder="选择" v-model="temp.typeIds">
                        <el-option
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                                v-for="item in types">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="库存" prop="stock">
                    <el-input v-model="temp.stock"></el-input>
                </el-form-item>
                <el-form-item label="单位" prop="unit">
                    <el-input v-model="temp.unit"></el-input>
                </el-form-item>
<!--                <el-form-item label="重量" prop="weight">-->
<!--                    <el-input v-model="temp.weight"></el-input>-->
<!--                </el-form-item>-->
                <el-form-item label="原价" prop="oldPrice">
                    <el-input v-model="temp.oldPrice"></el-input>
                </el-form-item>
                <el-form-item label="现价" prop="nowPrice">
                    <el-input v-model="temp.nowPrice"></el-input>
                </el-form-item>
                <el-form-item label="必须积分" prop="point">
                    <el-input v-model="temp.point"></el-input>
                </el-form-item>
                <el-form-item label="满免数量" prop="logFreeNum">
                    <el-input v-model="temp.logFreeNum"></el-input>
                </el-form-item>
                <el-form-item label="未满邮费" prop="logFee">
                    <el-input v-model="temp.logFee"></el-input>
                </el-form-item>
                <el-form-item label="排序,越大越靠前" prop="idx">
                    <el-input v-model="temp.idx"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="info">
                    <el-input v-model="temp.info"></el-input>
                </el-form-item>
                <el-form-item label="是否推荐" prop="status">
                    <el-select class="filter-item" placeholder="是否推荐" v-model="temp.top">
                        <el-option :key="item" :label="item" :value="index"
                                   v-for="(item,index) in  topOptions">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否上架" prop="status">
                    <el-select class="filter-item" placeholder="是否上架" v-model="temp.shelf">
                        <el-option :key="item" :label="item" :value="index"
                                   v-for="(item,index) in  shelfOptions">
                        </el-option>
                    </el-select>
                </el-form-item>
                <Sku :key="temp.id" :itemList="temp.skuItemList" :skuList="temp.skuList" @updateSku="updateSku" :qData="qData"></Sku>
                <el-form-item label="缩略图150*150" prop="minImg">
                    <el-upload
                            :auto-upload="true"
                            :before-upload="handleUpload"
                            :data="qData"
                            :file-list="minImgList"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="(file, fileList)=>handleImgRemove(minImgList,file)"
                            :on-success="(response, file, fileList)=>handleImgUploadSuccess(minImgList,file)"
                            action="http://upload.qiniup.com"
                            list-type="picture-card"
                            ref="minImgUpload">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="主图200*200" prop="midImg">
                    <el-upload
                            :auto-upload="true"
                            :before-upload="handleUpload"
                            :data="qData"
                            :file-list="midImgList"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="(file, fileList)=>handleImgRemove(midImgList,file)"
                            :on-success="(response, file, fileList)=>handleImgUploadSuccess(midImgList,file)"
                            action="http://upload.qiniup.com"
                            list-type="picture-card"
                            ref="midImgUpload">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="详情页(200kb以内)" prop="bigImg">
                    <el-upload
                            :auto-upload="true"
                            :before-upload="handleUpload"
                            :data="qData"
                            :file-list="bigImgList"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="(file, fileList)=>handleImgRemove(bigImgList,file)"
                            :on-success="(response, file, fileList)=>handleImgUploadSuccess(bigImgList,file)"
                            action="http://upload.qiniup.com"
                            list-type="picture-card"
                            ref="bigImgUpload">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>

                <el-dialog :visible.sync="dialogVisible" append-to-body>
                    <img :src="dialogImageUrl" alt="" width="100%">
                </el-dialog>
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="closeDialogForm">取消</el-button>
                <el-button @click="createData" type="primary" v-if="dialogStatus=='create'">确认</el-button>
                <el-button @click="updateData" type="primary" v-else>确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<style type="stylus">
    .filter-container {
        /*padding-bottom: 20px;*/
    }

    .filter-item {
        margin-bottom: 10px;
    }

    .filter-item.input {
        /*line-height: 60px*/
        margin-right: 10px;
    }
</style>

<script>
    import {list, remove, save, update,info} from '@/api/mall_goods'
    import waves from '@/directive/waves' // 水波纹指令
    import {all} from "../../../api/mall_type";
    import {domain, getToken} from '@/api/qiniu'
    import {listToStrs, strsToList} from '@/utils/imgUtil'
    import {mapGetters} from 'vuex'
    import {hasAuth} from '@/utils/auth'
    import Sku from '@/components/Sku'
    import {downExcel} from '@/utils/down.js'
    export default {
        name: 'test',
        directives: {
            waves
        },
        components:{
            Sku
        },
        data() {
            return {
                tableKey: 0,
                list: null,
                total: null,
                listLoading: true,
                types: null,
                listQuery: {
                    page: 1,
                    limit: 20,
                    order: 'id desc'
                    , name: null
                    , stock: null
                    , oldPrice: null
                    , nowPrice: null
                    , point: null
                    , logFreeNum: null
                    , logFee: null
                    , idx: null
                    , info: null
                    , top: null
                    , shelf: null
                },
                topOptions: ["否", "是"],
                shelfOptions: ["下架", "上架"],
                tagTypes: ['info', '', 'warning', 'danger', 'warning'],
                temp: {
                    id: null,
                    name: null,
                    unit:null,
                    typeIds:[],
                    stock: null,
                    oldPrice: null,
                    nowPrice: null,
                    minImg: null,
                    midImg: null,
                    bigImg: null,
                    top: null,
                    point: null,
                    logFreeNum: null,
                    logFee: null,
                    shelf: null,
                    idx: null,
                    info: null,
                    skuItemList: [],
                    skuList:[],
                }
                ,
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '修改',
                    create: '新增'
                }
                ,
                // 存在图片
                dialogImageUrl: '',
                dialogVisible: false,
                minImgList: [],
                midImgList: [],
                bigImgList: [],
                rules:
                    {
                        name: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        stock: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        oldPrice: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        nowPrice: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        minImg: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        midImg: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        bigImg: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        top: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'blur'
                            }
                        ]
                        ,
                        point: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        logFreeNum: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        logFee: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        shelf: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'blur'
                            }
                        ]
                        ,
                        idx: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        info: [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                    }
                ,
                downloadLoading: false,
                qData:
                    {
                        token: '',
                        key: ''
                    }
            }
        },
        activated() {
            this.getList()
            all().then(res => {
                this.types = res.data
            })
        },
        computed: {
            ...mapGetters([
                'perms'
            ]),
            canSave() {
                return hasAuth(this.perms, 'mall:goods:save')
            },
            canDelete() {
                return hasAuth(this.perms, 'mall:goods:delete')
            },
            canUpdate() {
                return hasAuth(this.perms, 'mall:goods:update')
            },
            canList() {
                return hasAuth(this.perms, 'mall:goods:list')
            }
        },
        methods: {
            updateSku(itemList,skuList){
                this.temp.skuItemList = itemList
                this.temp.skuList = skuList
            },
            getList() {
                this.listLoading = true
                list(this.listQuery).then(response => {
                    this.list = response.data.list
                    this.total = response.data.total
                    this.listLoading = false
                })
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            handleSizeChange(val) {
                this.listQuery.limit = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getList()
            },
            handleModifyStatus(row, status) {
                this.$message({
                    message: '操作成功',
                    type: 'success'
                })
                row.status = status
            },
            beforeFormShow(row) {
                this.resetTemp(row) // 更新数据
                // 存在图片
                this.initQiniu()

                // 存在图片字段转换图片地址显示
                this.initImgUrl()
            },
            afterFormShow(row) {

            },
            beforeFormCommit() {
                this.initImgName()// 图片转换
            },
            resetTemp(row) {

                this.temp = {}
                if (row) {
                    this.temp = Object.assign({}, row) // copy obj
                }

            },
            handleCreate() {
                this.beforeFormShow()
                this.resetTemp()
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.afterFormShow()
                    this.$refs['dataForm'].clearValidate()
                })
            },
            handleDelete(scope) {
                this.index = scope.$index
                // this.beforeFormShow(scope.row)
                // this.temp = Object.assign({}, row) // copy obj
                this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // this.$message({
                    //   type: 'success',
                    //   message: '删除成功!'
                    // })
                    this.deleteData()
                }).catch(() => {
                    this.$message({
                        type: 'error',
                        message: '删除失败'
                    })
                })
            },
            // 显示将图片名封装成可以展示状态集合
            initImgUrl() {
                this.minImgList = strsToList(this.temp.minImg, domain)
                this.midImgList = strsToList(this.temp.midImg, domain)
                this.bigImgList = strsToList(this.temp.bigImg, domain)
            },
            // 关闭显示窗口 重置图片地址 防止错乱
            resetImgUrl() {
                this.minImgList = []
                this.midImgList = []
                this.bigImgList = []
            },
            // 上传或者更新的时候从图片链接中获取图片名字
            initImgName() {
                this.temp.minImg = listToStrs(this.minImgList)
                this.temp.midImg = listToStrs(this.midImgList)
                this.temp.bigImg = listToStrs(this.bigImgList)
            },
            createData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            this.temp.json = true
                            save(this.temp).then(res => {
                                this.temp = res.data
                                this.list.unshift(this.temp)
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '创建成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            deleteData() {
                // const ids = [this.temp.id]
                const ids = [this.list[this.index].id]
                remove({ids: ids}).then(res => {
                    // 从当前队列中移除
                    this.list.splice(this.index, 1)
                    this.$notify({
                        title: '成功',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    })
                })
            },
            handleUpdate(scope) {
                this.index = scope.$index
                info(scope.row.id).then(res => {

                    this.beforeFormShow(res.data)
                    this.dialogStatus = 'update'
                    this.dialogFormVisible = true
                    this.$nextTick(() => {
                        this.$refs['dataForm'].clearValidate()
                    })
                })

            },
            updateData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            this.temp.json = true
                            update(this.temp).then(() => {
                                this.list.splice(this.index, 1, this.temp)
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '更新成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            closeDialogForm() {
                // 存在图片
                this.resetImgUrl()
                this.dialogFormVisible = false
            },
            handleDownload() {
                this.downloadLoading = true
                import('@/vendor/Export2Excel').then(excel => {
                    const tHeader = [
                        '序号'
                        ,
                        '产品名'
                        ,
                        '库存'
                        ,
                        '原价'
                        ,
                        '现价'
                        ,
                        '必须积分'
                        ,
                        '满免数量'
                        ,
                        '未满邮费'
                        ,
                        '排序,越大越靠前'
                        ,
                        '描述'
                        ,
                        '是否推荐'
                        ,
                        '是否上架'
                    ]
                    const filterVal = ['id'
                        , 'name'
                        , 'stock'
                        , 'oldPrice'
                        , 'nowPrice'
                        , 'point'
                        , 'logFreeNum'
                        , 'logFee'
                        , 'idx'
                        , 'info'
                        ,
                        'top'
                        ,
                        'shelf'
                    ]
                    const data = this.formatJson(filterVal, this.list)
                    excel.export_json_to_excel({
                        header: tHeader,
                        data,
                        filename: 'table-list'
                    })
                    this.downloadLoading = false
                })
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                        return v[j]
                    }
                ))
            },
            // 存在图片
            handleUpload(file) {
                this.qData.key = new Date().valueOf() + file.name
            },
            initQiniu() {
                // 获取七牛配置
                getToken().then(res => {
                    this.qData.token = res.data
                }).catch(error => {
                    console.log(error)
                })
            },
            handleImgUploadSuccess(imgList, file) {
                imgList.push({name: file.response.key, url: domain + file.response.key})
            },
            handleImgRemove(imgList, file) {
                for (var fn of imgList) {
                    if (fn.name === file.name) {
                        imgList.splice(imgList.indexOf(fn), 1)
                    }
                }
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url
                this.dialogVisible = true
            }
        }
    }
</script>
